<template>
    <div class="typewriter">
        <div class="content">
            <h3 class="text">
                {{ typewriterText }}
                <span></span>
            </h3>
        </div>
    </div>
</template>

<script setup>
import { poetryApi } from '@/api/public/poetry-api';
// ========================= 组件挂载前 =========================
onBeforeMount(() => {
    getData();
})
// ========================= 组件挂载后 =========================
onMounted(() => {
    // 延时执行
    setTimeout(() => {
        addText();
    },props.delayedTime);
});

// ========================= 组件卸载后 =========================
onUnmounted(() => {
    if (addIntervalId || deleteIntervalId) {
        clearInterval(addIntervalId);
        clearInterval(deleteIntervalId);
    }
});

const props = defineProps({
    // 文本内容
    text: {
        type: String,
        default: ''
    },

    // 延时多少时间执行 ms
    delayedTime: {
        type: Number,
        default: 1200
    },

    // 文本添加删除的间隔时间 ms
    intervalTime: {
        type: Number,
        default: 3000
    }, 

    // 文本添加删除的速度
    speedTime: {
        type: Number,
        default: 100
    }
})

// ========================= 获取数据 =========================
let resultText = ref('');
async function getData() {
    if(props.text != '') return;
    const res = await poetryApi.getScSj();
    resultText.value = res.data;
};

// ========================= 数据操作 =========================
let typewriterText = ref('');
let index = 0;
let addIntervalId = null;
let deleteIntervalId = null;

// 文本写入
function addText() {
    addIntervalId = setInterval(() => {
        let setText = '';
        props.text ? setText = props.text : setText = resultText.value;
        if (index < setText.length) {
            typewriterText.value += setText[index++];
        }else {
            setTimeout(() => {
                deleteText();
            }, props.intervalTime)
            clearInterval(addIntervalId);
        }
    }, props.speedTime);
};

// 文本删除
function deleteText() {
    deleteIntervalId = setInterval(() => {
        if(index > 0) {
            index--;
            typewriterText.value = typewriterText.value.slice(0, -1);
        }else {
            setTimeout(() => {
                addText();
            }, props.intervalTime)
            clearInterval(deleteIntervalId);
        }
    }, props.speedTime)
};
</script>

<style lang="scss" scoped>
    @import './typewriter.scss';
</style>